﻿using System.IO;
using System.Net;
using System.Text;

namespace Dan.CommonCore
{
    public class UrlRequest 
    {
        public static string HttpGet(string url, string data = "")
        {
            return HttpInner(url, "GET", data);
        }

        public static string HttpPost(string Url, string data = "")
        {
            return HttpInner(Url, "POST",data);
        }

        public static string HttpPut(string Url, string data = "")
        {
            return HttpInner(Url, "PUT",data);
        }

        public static string HttpDelete(string url, string data = "")
        {
            return HttpInner(url, "DELETE",data);
        }        

        public static string HttpInner(string Url, string method, string data = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = method;
            request.ContentType = "application/json";            
            request.ContentLength = (long)Encoding.UTF8.GetByteCount(data);
            
            if (!string.IsNullOrEmpty(data))
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(data);
                    streamWriter.Flush();
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string end = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return end;
        }

       
    }
}